package com.emm.yixun.website.controller.customer;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.excel.FastExcel;
import com.emm.yixun.common.exception.BusinessException;
import com.emm.yixun.common.model.CustomerError;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.CustomerErrorDto;
import com.emm.yixun.common.model.dto.CustomerModel;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.common.utils.ExcelUtils;
import com.emm.yixun.customer.service.CustomerErrorServiceFacade;
import com.emm.yixun.customer.service.CustomerExcelServiceFacade;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.vo.CustomerImportVo;


@RequestMapping(value = "/customer/import/")
@Controller
public class CustomerImportController extends BaseController<CustomerModel> {
	
	@Autowired
	private CustomerExcelServiceFacade customerExcelServiceFacade;
	@Autowired
	private CustomerServiceFacade customerServiceFacade;
	@Autowired
	private CustomerErrorServiceFacade customerErrorServiceFacade;
	
	/**
	* 方法描述 : 导入EXCEL
	* 创建者：ThinkPad 
	* 项目名称： emm-website
	* 类名： CustomerImportController.java
	* 版本： v1.0
	* 创建时间： 2016年5月25日 下午3:39:50
	* @param response
	* @param multipartFile
	* @param request
	* @return java.util.Map<String, String>
	 */
	@RequestMapping(value = "importExcel")
	public @ResponseBody AjaxRes importHouseInfo(HttpServletRequest request,
			@RequestParam("multipartFile")MultipartFile multipartFile,
			HttpServletResponse response,String projectId){
		AjaxRes ar = getAjaxRes();
		response.setContentType("text/html; charset=utf-8");
		try {
			/**
			 * 1.解析Excel数据并转为java实体bean
			 * 2.手机号码表内查重，数据验证(需求编号：406)
			 * 3.验证不通过数据进行日志记录
			 * 4.验证通过数据入库
			 * 5.下载错误数据
			*/
			User user = ShiroUtil.getCurrentUser();
			//解析Excel数据并转为java实体bean
			FastExcel fastExcel=new FastExcel(multipartFile.getInputStream());
			fastExcel.setStartRow(1);
			fastExcel.setSheetName("客户批量导入");
			List<CustomerModel> customerList = fastExcel.parse(CustomerModel.class);
			fastExcel.close();
			
			//重复行下标
			Map<String,String> repeatMap=findRepeatPhone(customerList);
			CustomerImportVo result=addCustomer(customerList,repeatMap,user,Long.valueOf(projectId));
			ar.setSucceed(result);
			
		} catch (BusinessException e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(e.getErrorMsg());
		} catch (Exception e) {
			logger.error("importHouseInfo error: ", e);
			ar.setFailMsg(e.getMessage());
		}
		return ar;
	}
	//查找重复电话号码
	private Map<String,String> findRepeatPhone(List<CustomerModel> list)throws Exception{
		Map<String,String> phoneMap=new  HashMap<String,String>();
        Map<String,String> repeatPhonesMap=new HashMap<String,String>();
		for(int i = 0; i < list.size(); i++){
			CustomerModel customerModel =list.get(i);
			//电话1
			String customerPhone=customerModel.getCustomerPhone();
			//电话2
			String phone=customerModel.getPhone();
			if(StringUtils.isBlank(customerPhone) || StringUtils.isBlank(phone)){
				continue;
			}
			if(phoneMap.containsKey(customerPhone)){
				//电话1重复则放入重复的map，同时去重复
				repeatPhonesMap.put(customerPhone, customerPhone);
			}
			phoneMap.put(customerPhone, customerPhone);
			if(phoneMap.containsKey(phone)){
				//电话2重复则放入重复的map，同时去重复
				repeatPhonesMap.put(phone, phone);
			}
			phoneMap.put(phone, phone);
		}
		return repeatPhonesMap;
	}
	
	private CustomerImportVo addCustomer(List<CustomerModel> customerList,Map<String,String> repeatMap,User user,Long projectId){
		List<CustomerModel> errorList=new ArrayList<CustomerModel>();
		int addCount=0;
		for(CustomerModel cm : customerList){
			cm.setMerchantId(user.getMerchantId());
			cm.setProjectId(projectId);
			Map<String,Object> resultMap=validateCustomerModel(cm,repeatMap);
			Boolean isSuccess=(Boolean)resultMap.get("isSuccess");
			if(!isSuccess){
				String error=(String)resultMap.get("error");
				cm.setErrorInfo(error);
				errorList.add(cm);
				continue;
			}
			CustomerDto customerDto=(CustomerDto)resultMap.get("customerDto");
			customerDto.setProjectId(projectId);
			customerDto.setUserCode(user.getUserCode());
			customerDto.setUserId(user.getId());
			customerDto.setMerchantId(user.getMerchantId());
			customerDto.setCreateUserId(user.getId());
			customerDto.setDelFlag("0");
			customerDto.setUpdateUserId(user.getId());
			customerDto.setUpdateTime(new Date());
			try {
				customerServiceFacade.allAddCustomer(customerDto);
				addCount++;
			} catch (Exception e) {
				logger.error("addCustomer error: ", e);
				cm.setErrorInfo(e.getMessage());
				errorList.add(cm);
			}
		}
		
		//保存错误信息
		String batchId=UUID.randomUUID().toString();
		if(errorList.size()>0){
			List<CustomerError> list=new ArrayList<CustomerError>();
			for(CustomerModel cm : errorList){
				String cmStr = JSON.toJSONString(cm);
				JSONObject object=JSONObject.parseObject(cmStr);
				CustomerError ce=new CustomerError();
				ce.setBatchId(batchId);
				ce.setCreateUserId(user.getId());
				ce.setMerchantId(user.getMerchantId());
				ce.setCreateTime(new Date());
				ce.setUpdateTime(new Date());
				ce.setDelFlag("0");
				ce.setRowData(object.toJSONString());
				list.add(ce);
			}
			customerErrorServiceFacade.insertByBatch(list);
		}
		CustomerImportVo ci=new CustomerImportVo();
		ci.setSuccessCount(addCount);
		ci.setErrorCount(errorList.size());
		ci.setBatchId(batchId);
		return ci;
	}
	
	private Map<String,Object> validateCustomerModel(CustomerModel cm,Map<String,String> repeatMap){
		Map<String,Object> resultMap=new HashMap<String,Object>();
		StringBuffer error=new StringBuffer("");
		//电话1
		String customerPhone=cm.getCustomerPhone();
		//电话2
		String phone=cm.getPhone();
		String zhengjianhaoma = cm.getZhengjianhaoma();
		String familyValueOneThree = cm.getFamilyValueOneThree();
		String familyValueTwoThree = cm.getFamilyValueTwoThree();
		String familyValueThreeThree = cm.getFamilyValueThreeThree();
		String familyValueFourThree = cm.getFamilyValueFourThree();
		boolean isSuccess=true;
		if(StringUtils.isNotBlank(customerPhone) && repeatMap.containsKey(customerPhone)){
			isSuccess=false;
			error.append("联系电话表内重复;");
		}
		if(StringUtils.isNotBlank(phone) && repeatMap.containsKey(phone)){
			isSuccess=false;
			error.append("手机号表内重复;");
		}
		if(StringUtils.isNotBlank(zhengjianhaoma)&&zhengjianhaoma.length()>18){
			isSuccess=false;
			error.append("证件号码不能超过18位");
		}
		if(StringUtils.isNotBlank(familyValueOneThree)&&familyValueOneThree.length()>18){
			isSuccess=false;
			error.append("证件号码不能超过18位");
		}
		if(StringUtils.isNotBlank(familyValueTwoThree)&&familyValueTwoThree.length()>18){
			isSuccess=false;
			error.append("证件号码不能超过18位");
		}
		if(StringUtils.isNotBlank(familyValueThreeThree)&&familyValueThreeThree.length()>18){
			isSuccess=false;
			error.append("证件号码不能超过18位");
		}
		if(StringUtils.isNotBlank(familyValueFourThree)&&familyValueFourThree.length()>18){
			isSuccess=false;
			error.append("证件号码不能超过18位");
		}
		Response<CustomerDto> response=customerExcelServiceFacade.validateCustomerModel(cm);
		//当表内重复验证通过，则继续判断其它规则是否通过
		if(isSuccess){
			isSuccess=response.isSuccess();
		}
		if(isSuccess){
			resultMap.put("isSuccess", isSuccess);
			resultMap.put("customerDto", response.getEntity());
		}else{
			if(!response.isSuccess()){
				error.append(response.getResultMessage());
			}
			resultMap.put("isSuccess", isSuccess);
			resultMap.put("error", error.toString());
		}
		return resultMap;
	}
    
	
	@RequestMapping(value = "download")
	public void downloadExcelModel(HttpServletResponse response,String batchId, String type){
		try {
			  CustomerErrorDto customerErrorDto=new CustomerErrorDto();
			  customerErrorDto.setBatchId(batchId);
			  ResponseList<CustomerError> list=customerErrorServiceFacade.findByDto(customerErrorDto);
			  if(list.isSuccess() && null!=list){
				  List<CustomerError> ceList=list.getEntity();
				  List<CustomerModel> cmList=new ArrayList<CustomerModel>();
				  for(CustomerError ce : ceList){
					  String rowData=ce.getRowData();
					  CustomerModel cm=JSON.parseObject(rowData, CustomerModel.class);
					  cmList.add(cm);
				  }
				  String sheetName = "客户批量导入";
				  if("subscribe".equals(type)) {
					  sheetName = "认购";
				  }
				  HSSFWorkbook wb=ExcelUtils.createExcel(cmList, sheetName);
			      String mimetype = "application/x-msdownload";
			      String downFileName = "excel-"+DateUtils.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS)+".xls";
			      String inlineType = "attachment"; 
			      response.setHeader("Content-Disposition", inlineType  + ";filename=\"" + downFileName + "\"");
			      OutputStream out=response.getOutputStream();
			      response.setContentType(mimetype);
			      wb.write(out);
			  }
			  
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

}
